package com.vhall.component.plugin.common.utils;

import com.vhall.component.framework.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.mozilla.universalchardet.UniversalDetector;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author yuanzh
 * @date 2021/12/3
 */
@Slf4j
public class FileUtil {

    private FileUtil() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 获取文件编码
     *
     * @param file 文件
     * @return 文件编码
     * @throws IOException 异常
     */
    public static String getFileCharset(File file) throws IOException {
        return getFileCharset(new FileInputStream(file));
    }

    /**
     * 获取文件编码
     *
     * @param filePath 文件全路径
     * @return 文件编码
     * @throws IOException 异常
     */
    public static String getFileCharset(String filePath) throws IOException {
        return getFileCharset(new FileInputStream(new File(filePath)));
    }

    /**
     * 获取文件编码
     *
     * @param inputStream 文件流
     * @return 文件编码
     * @throws IOException 异常
     */
    public static String getFileCharset(InputStream inputStream) throws IOException {
        String charset = StandardCharsets.UTF_8.toString();
        byte[] buf = new byte[4096];
        UniversalDetector detector = new UniversalDetector(null);
        int nRead;
        while ((nRead = inputStream.read(buf)) > 0 && !detector.isDone()) {
            detector.handleData(buf, 0, nRead);
        }

        detector.dataEnd();

        String detectedCharset = detector.getDetectedCharset();
        if (Objects.nonNull(detectedCharset) && detectedCharset.length() > 0) {
            charset = detectedCharset;
        }
        return charset;
    }

    /**
     * MultipartFile转file
     *
     * @param multipartFile 文件
     * @return
     */
    public static File multiToFile(MultipartFile multipartFile) {
        // 选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferTo()方法 。
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename)) {
                return null;
            }
            Assert.notNull(originalFilename, "原文件名不存在");
            int lastPointIndex = originalFilename.lastIndexOf(".");
            String suffix = originalFilename.substring(lastPointIndex + 1);
            String prefix = originalFilename.substring(0, lastPointIndex + 1);
            file = File.createTempFile(prefix, suffix);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            log.error("转换异常", e);
        }
        return file;
    }

}
